#include "connection.h"
#include "lidar.pb.h"
#include "../form/log/QsLog/QsLog.h"
#include "../form/gloab/globalobserver.h"

Connection* Connection::instance = new Connection();

Connection::Connection()
    :m_connection(QSqlDatabase::addDatabase("QODBC"))
    ,m_query(new QSqlQuery(m_connection))
{
    // QObject::connect(this, &Connection::Sig_dataBaseConnected, GlobalObserver::getInstance(), &GlobalObserver::Sig_dataBaseConnected);
    // QObject::connect(this, &Connection::Sig_dataBaseDisConnected, GlobalObserver::getInstance(), &GlobalObserver::Sig_dataBaseDisConnected);
}

bool Connection::isConnect()
{
    return m_connection.isOpen();
}

void Connection::closeConnect()
{
    if(m_connection.isOpen()){
        m_connection.close();
        emit Sig_dataBaseDisConnected();
    }
}
// 释放数据库连接资源
Connection::~Connection(){
    if(m_query)
        m_query->clear();
}

// 连接数据库
bool Connection::connect(QString ip, unsigned short port, QString user, QString password,
                         QString dbname){

    m_connection.setHostName(ip);
    m_connection.setPort(port);
    m_connection.setDatabaseName(dbname);
    m_connection.setUserName(user);
    m_connection.setPassword(password);

    if(m_connection.open()){
        emit Sig_dataBaseConnected();
    }
    return m_connection.open();
}
// 更新操作 insert、delete、update
bool Connection::update(QString sql){
    if (!m_query->exec(sql))
    {

        qDebug()<<"数据库update失败： "<<m_query->lastError().text();
        return false;
    }
    return true;
}
// 查询操作 select
QList<QVariantMap> Connection::query(QString sql){
    QList<QVariantMap> resultList;
    if (!m_query->exec(sql))
    {
        emit Sig_dataBaseDisConnected();
        qDebug()<<"数据库query失败： "<<m_query->lastError().text();
        return resultList;
    }

    //查询到的语句放入QList<QVariantMap>
    while (m_query->next()) {
        QVariantMap row;
        QSqlRecord record = m_query->record();
        for (int i = 0; i < record.count(); ++i) {
            row[record.fieldName(i)] = m_query->value(i);
        }
        resultList.append(row);
    }
    return  resultList;
}

Connection *Connection::getInstance()
{
    return instance;
}
